from create_import import *
from table_list import *


def create_controller(table: str):
    """
    创建Controller
    """
    _current = "controller"
    param = Params(table)  # 通过表名置换公共参数
    _request_mapping_path = "/".join(table.lower().split("_"))
    _class_name = param.class_name_controller  # 当前类名
    _class_name_mapper = param.class_name_mapper  # 当前类的Mapper名
    _class_name_service = param.class_name_service  # 当前类的Service名
    _package_name = f"package {param.package_name_basic}.{_current};"  # 当前包名
    _java_output_path = f"{param.output_java_path_basic}/{_current}"  # java文件路径
    # print(f">>输出路径{_java_output_path}")
    if not os.path.exists(_java_output_path):
        os.makedirs(_java_output_path)
    _java_output_file = f"{_java_output_path}/{_class_name}.java"
    _print_output = output(_java_output_file)  # print 的 output
    _url_output_path = f"{local_dir}/{table}/"
    if not os.path.exists(_url_output_path):
        os.makedirs(_url_output_path)
    _url_output_file = f"{_url_output_path}/{table}.txt"
    _url_output = output(_url_output_file)
    urls = ["hello", "save", "page", "removeBatchByIds", "updateById"]

    def printf(val):
        print(val, file=_print_output)

    def printurl():
        for url in urls:
            print(
                f"http://localhost:24010/{_request_mapping_path}/{url}",
                file=_url_output,
            )

    hello = f"""
	@RequestMapping("/hello")
	public String hello(@RequestParam(value = "channel", required = false) String channel) {{
		try {{
			log.info("执行{{}}/hello,请求参数{{}}", REQUESTMAPPING, channel);
			log.info("完成hello请求");
			return "hello " + channel;
		}} catch (Exception e) {{
			log.error("异常{{}}/hello,请求参数{{}}", REQUESTMAPPING, channel);
			log.error(e);
			return null;
		}}
	}}
    """

    save = f"""
	@RequestMapping("/save")
	public Response save(@RequestBody {param.class_name_basic} {param.class_name_basic_param}) {{
        try {{
            log.info("执行{{}}/save,请求参数{{}}", REQUESTMAPPING, {param.class_name_basic_param});
            boolean result = this.{param.class_name_service_param}.save({param.class_name_basic_param});
            log.info("完成save请求,{{}}", result);
            return new Response().success(result);
        }} catch (Exception e) {{
			log.error("异常{{}}/save,请求参数{{}}", REQUESTMAPPING, {param.class_name_basic_param});
			log.error(e);
			return new Response().failure(e.getMessage());
		}}
	}}
    """

    page = f"""
	@RequestMapping("/page")
	public Response page(@RequestBody PageVo<{param.class_name_basic}> pageVo) {{
		try {{
			log.info("执行{{}}/page,请求参数{{}}", REQUESTMAPPING, pageVo);
			IPage<{param.class_name_basic}> page = new Page<>(pageVo.getCurrent(), pageVo.getSize());
			Wrapper<{param.class_name_basic}> wrapper = new LambdaQueryWrapper<{param.class_name_basic}>(pageVo.getEntity())
					.orderByDesc({param.class_name_basic}::getDataTime);
			IPage<{param.class_name_basic}> result = this.{param.class_name_service_param}.page(page, wrapper);
			log.info("完成page请求,{{}}", result);
			return new Response().success(result);
		}} catch (Exception e) {{
			log.error("异常{{}}/page,请求参数{{}}", REQUESTMAPPING, pageVo);
			log.error(e);
			return new Response().failure(e.getMessage());
		}}
	}}
    """

    removeBatchByIds = f"""
	@RequestMapping("/removeBatchByIds")
	public Response removeBatchByIds(@RequestBody List<String> ids) {{
		try {{
			log.info("执行{{}}/removeBatchByIds,请求参数{{}}", REQUESTMAPPING, ids);
			boolean result = this.{param.class_name_service_param}.removeBatchByIds(ids);
			log.info("完成removeBatchByIds请求,{{}}", result);
			return new Response().success(result);
		}} catch (Exception e) {{
			log.error("异常{{}}/removeBatchByIds,请求参数{{}}", REQUESTMAPPING, ids);
			log.error(e);
			return new Response().failure(e.getMessage());
		}}
	}}
    """

    updateById = f"""
	@RequestMapping("/updateById")
	public Response updateById(@RequestBody {param.class_name_basic} {param.class_name_basic_param}) {{
		try {{
			if ({param.class_name_basic_param} == null || {param.class_name_basic_param}.getUuid() == null) {{
				return new Response().failure("没有更新数据！");
			}}
			log.info("执行{{}}updateById,请求参数{{}}", REQUESTMAPPING, {param.class_name_basic_param});
			boolean result = this.{param.class_name_service_param}.updateById({param.class_name_basic_param});
			log.info("完成updateById请求,{{}}", result);
			return new Response().success(result);
		}} catch (Exception e) {{
			log.error("异常{{}}/updateById,请求参数{{}}", REQUESTMAPPING, {param.class_name_basic_param});
			log.error(e);
			return new Response().failure(e.getMessage());
		}}
	}}
    """
    demoblock = f"""{_package_name}

import java.util.List;    

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.log4j.Log4j2;

import http.api.PageVo;
import http.api.Response;
import {param.package_name_basic}.entity.{param.class_name_basic};
import {param.package_name_basic}.mapper.{_class_name_mapper};
import {param.package_name_basic}.service.{_class_name_service};


@RestController
@RequestMapping("/{_request_mapping_path}")
@Log4j2
public class {_class_name} {{
    private static final String REQUESTMAPPING = "/{_request_mapping_path}";

    @Autowired
	private {param.class_name_service} {param.class_name_service_param};
    """
    printf(demoblock)  # import block

    printf(hello)
    printf(save)
    printf(page)
    printf(removeBatchByIds)
    printf(updateById)

    printf("}")
    # print(f"{param.table}创建{_current} impl - 完成")
    print(f'"{_package_name[_package_name.find(" ")+1 : -1 :]}"')
    printurl()


if __name__ == "__main__":
    for table in table_list:
        create_controller(table)
        # break
